package org.darchitect.nn.som.ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;

import javax.swing.JPanel;

public class ColorPanel extends JPanel {
	
	private static final long serialVersionUID = 1L;
	private int width;
	private double w[][][];
	private String labels[];
	private ArrayList<Integer> labelPos[][];
	private ArrayList<Point2D> selectedPoints = new ArrayList<Point2D>();
	int cellWidth;
	
	public ColorPanel(double w[][][]) {
		this.w = w;
		int cons = 10;
		int width = w.length * cons;
		while (width > 580)
			width = w.length * --cons;
		this.width = width;
		Dimension dim = new Dimension(width, width);
		setPreferredSize(dim);
		setSize(dim);
		setMaximumSize(dim);
		setMinimumSize(dim);
	}
	
	public void setWeights(double w[][][]) {
		this.w = w;
		repaint();
	}
	
	public void addSelectedPoint(Point2D p) {
		selectedPoints.add(p);
	}
	
	public void removeSelectedPoint(Point2D p) {
		selectedPoints.remove(p);
	}
	
	public int getCellWidth() {
		return cellWidth;
	}
	
	public void setLabels(String labels[], ArrayList<Integer> labelPos[][]) {
		this.labels = labels;
		this.labelPos = labelPos;
		repaint();
	}
	
	@Override
	public void paint(Graphics g) {
		super.paint(g);
		double s = width * 1. / w.length;
		cellWidth = (int)s;
		ArrayList<Integer> l;
		for (int i = 0; i < w.length; i++) {
			for (int j = 0; j < w.length; j++) {
				int rr = (int)((w[i][j][0] + 1) * 128);
				int gg = (int)((w[i][j][1] + 1) * 128);
				int bb = (int)((w[i][j][2] + 1) * 128);
				g.setColor(new Color(rr, gg, bb));
				g.fillRect((int)(i*s), (int)(j*s), (int)s, (int)s);
				
				Rectangle2D rect = new Rectangle((int)(i*s), (int)(j*s), (int)s, (int)s);
				for (Point2D p : selectedPoints)
					if (rect.contains(p)) {
						g.setColor(Color.GREEN);
						g.drawRect((int)(i*s) + 1, (int)(j*s) + 1, (int)s - 3, (int)s - 3);
						g.setColor(Color.BLACK);
						g.drawRect((int)(i*s), (int)(j*s), (int)s - 1, (int)s - 1);
					}
				
				if (labels != null && labelPos != null) {
					l = labelPos[i][j];
					g.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 8));
					if (l != null) {
						g.setColor(new Color(0, 0, 0));
//						g.drawString(l.size()+"", (int)(i*s), (int)(j*s));
						for (int k = 0; k < 1; k++) {
							g.drawString(l.get(k).toString(), (int)(i*s), (int)(j*s));
						}
					}
				}
			}
		}
	}
	
}
